/**
 * 课程列表服务
 */

const dayjs = require('dayjs');
const { existsById } = require('../db/class_list');
const { getIntersection, addCourse, searchCourseList, updateCourse, getById, deleteCourse, searchCourseListForSelector } = require('../db/course_list');
const { getTeacherStatusById } = require('../db/teachers');

/**
 * 添加课表
 * @param {*} ctx 
 */
const add = async ctx => {
    try {
        const obj = ctx.request.body;
        const { from_date, end_date, class_id, teacher_id } = obj;
        const from = new Date(from_date);
        const end = new Date(end_date);
        if (from >= end) {
            return ctx.body = {
                code: 0,
                msg: '开始时间不得大于等于结束时间'
            }
        }
        if (from <= new Date()) {
            return ctx.body = {
                code: 0,
                msg: '开始时间不得小于等于当前时间'
            }
        }
        const classInfo = await existsById(class_id);
        if (!classInfo) {
            return ctx.body = {
                code: 0,
                msg: '班级不存在，请勿非法操作'
            }
        }
        const teacher = await getTeacherStatusById(teacher_id);
        if (!teacher) {
            return ctx.body = {
                code: 0,
                msg: '教师不存在，请勿非法操作'
            }
        }
        if (!teacher.status) {
            return ctx.body = {
                code: 0,
                msg: '此教师已离职，无法授课'
            }
        }
        const intersection = await getIntersection(obj);
        if (intersection) {
            const { class_id: cid, from_date: f, end_date: e } = intersection;
            return ctx.body = {
                code: 0,
                msg: `此${cid === class_id ? '班级' : '教师'}在${dayjs(f).format('YYYY-MM-DD HH:mm:ss')}至${dayjs(e).format('YYYY-MM-DD HH:mm:ss')}有课程`
            }
        }
        await addCourse(obj);
        ctx.body = {
            code: 1,
            msg: '课表添加成功'
        }
    } catch (error) {
        ctx.app.emit('error', error);
        ctx.body = {
            code: 0,
            msg: '课表添加失败，请稍后再试'
        }
    }
}

/**
 * 修改课表
 * @param {*} ctx 
 */
const update = async ctx => {
    try {
        const obj = ctx.request.body;
        const { from_date, end_date, class_id, teacher_id } = obj;
        const from = new Date(from_date);
        const end = new Date(end_date);
        if (from >= end) {
            return ctx.body = {
                code: 0,
                msg: '开始时间不得大于等于结束时间'
            }
        }
        if (from <= new Date()) {
            return ctx.body = {
                code: 0,
                msg: '开始时间不得小于等于当前时间'
            }
        }
        const classInfo = await existsById(class_id);
        if (!classInfo) {
            return ctx.body = {
                code: 0,
                msg: '班级不存在，请勿非法操作'
            }
        }
        const teacher = await getTeacherStatusById(teacher_id);
        if (!teacher) {
            return ctx.body = {
                code: 0,
                msg: '教师不存在，请勿非法操作'
            }
        }
        if (!teacher.status) {
            return ctx.body = {
                code: 0,
                msg: '此教师已离职，无法授课'
            }
        }
        const { id, ...rest } = obj;
        const intersection = await getIntersection(obj, id);
        if (intersection) {
            console.log(intersection);
            const { class_id: cid, from_date: f, end_date: e } = intersection;
            return ctx.body = {
                code: 0,
                msg: `此${cid === class_id ? '班级' : '教师'}在${dayjs(f).format('YYYY-MM-DD HH:mm:ss')}至${dayjs(e).format('YYYY-MM-DD HH:mm:ss')}有课程`
            }
        }
        await updateCourse(id, rest);
        ctx.body = {
            code: 1,
            msg: '课表修改成功'
        }
    } catch (error) {
        ctx.app.emit('error', error);
        ctx.body = {
            code: 0,
            msg: '课表修改失败，请稍后再试'
        }
    }
}

/**
 * 搜索课程列表
 * @param {*} ctx 
 */
const search = async ctx => {
    try {
        const [data, total] = await searchCourseList(ctx.request.query);
        const date = new Date();
        for (const item of data) {
            //如果开始时间大于当前时间则未开始
            if (new Date(item.from_date) > date) {
                item.status = '未开始';
            }
            //如果结束时间小于当前时间则已结束
            else if (new Date(item.end_date) < date) {
                item.status = '已结束';
            }
            else {
                item.status = '上课中';
            }
        }
        ctx.body = {
            code: 1,
            data,
            total
        }
    } catch (error) {
        ctx.app.emit('error', error);
        ctx.body = {
            code: 0,
            msg: '课程列表搜索失败，请稍后再试'
        }
    }
}

/**
 * 为了选择器搜索课程列表
 * @param {*} ctx 
 */
const searchForSelector = async ctx => {
    try {
        const obj = ctx.request.query;
        //要么是本人，要么教师ID不传
        if (obj.isSelf == 'true') {
            obj.teacher_id = ctx.state.user.id;
        } else {
            obj.self_id = ctx.state.user.id;
        }
        const [data, total] = await searchCourseListForSelector(obj);
        const date = new Date();
        for (const item of data) {
            //如果开始时间大于当前时间则未开始
            if (new Date(item.from_date) > date) {
                item.status = '未开始';
            }
            //如果结束时间小于当前时间则已结束
            else if (new Date(item.end_date) < date) {
                item.status = '已结束';
            }
            else {
                item.status = '上课中';
            }
        }
        ctx.body = {
            code: 1,
            data,
            total
        }
    } catch (error) {
        ctx.app.emit('error', error);
        ctx.body = {
            code: 0,
            msg: '课程列表搜索失败，请稍后再试'
        }
    }
}

/**
 * 删除课程
 * @param {*} ctx 
 */
const deleteC = async ctx => {
    try {
        const { id } = ctx.request.params;
        const obj = await getById(id);
        if (!obj) {
            return ctx.body = {
                code: 0,
                msg: '您要删除的数据不存在'
            }
        }
        const start = new Date(obj.from_date);
        if (start >= new Date()) {
            return ctx.body = {
                code: 0,
                msg: '此课程已开始或结束，无法删除'
            }
        }
        await deleteCourse(id);
        ctx.body = {
            code: 1,
            msg: '课程删除成功'
        }
    } catch (error) {
        ctx.app.emit('error', error);
        ctx.body = {
            code: 0,
            msg: '课程删除失败，请稍后再试'
        }
    }
}

module.exports = {
    add,
    search,
    update,
    deleteC,
    searchForSelector
}